package work.sajor.wechatpush.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import work.sajor.wechatpush.service.WechatService;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@RestController
@RequestMapping("")
public class WechatController {


    @Autowired
    private WechatService service;

    /**
     * 完成两个工作：
     * 1，接收普通消息，被动返回。
     * 2，校验配置，返回echostr表示是验证成功,微信会发过来这几个参数，用于校验
     * String signature, String timestamp, String nonce, String echostr
     */
    @RequestMapping("/getMsg")
    public String checkValid(String signature, String timestamp, String nonce, String echostr, HttpServletRequest req) {
        String requestMethod = req.getMethod();
        if (requestMethod.equals("POST")) { // 处理 POST 请求
            System.out.println("==进入post方法==:");
            Map<String, String> msgMap = service.parseXmlData2Map(req);
            String s1 = service.parseDataToXml(msgMap);
            System.out.println("==解析的map:=="+msgMap + "==返回的xml:==" + s1);
            return s1;
        } else if (requestMethod.equals("GET")) { // 处理 GET 请求
            System.out.println("signature:"+signature + "==" +"timestamp:" + timestamp +"nonce:"+ nonce +"echostr"+echostr);
//            return service.checkSignature(timestamp, nonce, signature) ? echostr : "校验失败";
            return echostr;
        } else {
            return "不是 GET 和 POST";
        }
    }

//    @PostMapping("/getMsg")
//    public String getMsg(HttpServletRequest req) {
//        Map<String, String> msgMap = service.parseXmlData2Map(req);
//        String s1 = service.parseDataToXml(msgMap);
//        System.out.println(msgMap + "==返回信息==" + s1);
//        return s1;
//    }
}
